<template>
  <div class="homeDetail">
    <header>
      <i @click="goBack()"></i>
      <!-- <span @click='isShowMc=true' v-if='!showEdit'></span> -->
      <router-link :to='{name: "setInfo",query:{id: cid}}' v-if='showEdit'></router-link>
      <div class="vdo" @click.stop='controlShow'>
        <!-- <video id='vdo' :src="currentVideo.vdoUrl" :poster="img" @timeupdate='(!timeDrage) && playTime()' -->
        <video id='vdo' :src="currentVideo.vdoUrl" @timeupdate='(!timeDrage) && playTime()' @loadedmetadata='getallTime'>
          您的浏览器不支持 video 标签。
        </video>
        <div class='controls' @click.stop='stopControl' v-show='currentVideo.vid'>
          <img @click='play(infoObj)' :src="playImg" width='17' alt="">
          <div class='progress'>
            <div class='range'></div>
            <input type='range' min='0' step='0.1' :max='maxVal' :value='rangeVal' class='rangeInput' @touchstart='playRange($event)' />
          </div>
          <div class='time'>
            {{vdotime.currentTime}} / {{vdotime.allTime}}
          </div>
          <img @click='gofullScreen' src="../../image/icon_screen.png" width='17' alt="">
        </div>
      </div>

    </header>
    <div class="title">
      <div>
        <h3>{{infoObj.course_name}}</h3>
        <div style=" color: rgba(0, 0, 0, 0.4);font-size: 10px;margin: 0.04rem 0rem 0.035rem">视频名称：{{currentVideo.vname}}</div>
        <span>
          <img src="../../image/title.png" alt="" style="height: 0.18rem;">
          主讲老师: {{infoObj.teacher_name}}
        </span>
        <span>
          <img src="../../image/title.png" alt="" style="height: 0.18rem;">
          综合评分：{{infoObj.score}}</span>
      </div>
      <div class="price">
        <b>{{infoObj.iffree=='free'?'0.00':infoObj.charge}}</b>
        <b style="font-size: 10px;
            margin-top: -8px;">RMB</b>
        <img v-show='!isShowCreateSingle' @click="showComment" class="commentIcon" src="../../image/comment.png" alt="">

      </div>
    </div>
    <div class='box'>
      <div class="nav">
        <div :class="show.tab0?'active':''" @click='tabToggle(0)'>
          <a class="">
            <b>课程介绍</b>
          </a>
        </div>
        <div :class="show.tab1?'active':''" @click='tabToggle(1)'>
          <a class="">
            <b>课程大纲</b>
          </a>
        </div>
        <div :class="show.tab2?'active':''" @click='tabToggle(2)'>
          <a class="">
            <b>用户评论</b>
          </a>
        </div>
      </div>
      <div class="swiper-container swipe" id="outSwiper">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-if='show.tab0'>
            <course-introduction></course-introduction>
          </div>
          <div class="swiper-slide" v-if='show.tab1'>
            <router-link :to='{name:"uploadFile",query: {id:this.$route.query.id}}' class="remind" v-if='isUpload'>
              <img src="../../image/uploadVideo.png" alt="">
            </router-link>
            <video-playback @getVdoUrl='getVdoByChild'></video-playback>
          </div>
          <div class="swiper-slide" v-if='show.tab2'>
            <!-- 直播课时  暂时不要 -->
            <ul class="commentList">
              <Loadmore :bottom-method="loadBottom" :bottom-all-loaded="allLoaded" ref="loadmore" :autoFill="false">
                <div class='mcCommentList' v-if="list.length<1">
                  <!-- <img src="../../image/no_collection@2x.png" width='110' alt=""> -->
                  <p>暂无评论!</p>
                </div>
                <li v-for='(item,index) in list' :key='index' v-if="list.length>0">
                  <div class="name">
                    <h4>{{item.username}}</h4>
                    <i>{{item.time | formatDate}}</i>
                  </div>
                  <el-rate v-model="item.value5" disabled text-color="#ff9900" score-template="{value}" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                    @change="rate(commentObj.grade)">
                  </el-rate>
                  <p class='content'>
                    {{item.content}}
                  </p>
                </li>
              </Loadmore>
            </ul>
          </div>
        </div>
      </div>
      <div class="mc" v-show="isShowMc" @click.stop='isShowMc=false'>
        <div @click.stop='isShowMc=true'>
          <h3>分享给其他朋友</h3>
          <div>
            <a>
              <img src="../../image/icon_weixin_share.png" width="36" height="36" alt="">
            </a>
            <a>
              <img src="../../image/icon_xinlang_share.png" width="36" height="36" alt="">
            </a>
            <a>
              <img src="../../image/icon_pengyouquan_share.png" width="36" height="36" alt="">
            </a>
          </div>
          <a class="cancel" @click.stop='isShowMc=false'>
            取 消
          </a>
        </div>
      </div>
      <!-- 评论蒙层 -->
      <div class="mcComment" v-show="isShowComment" @click.stop='isShowComment=false'>
        <div class='bottom' @click.stop='isShowComment=true'>
          <div class="gradebox" v-show='gradeStatus'>
            <span>用户打分:</span>
            <el-rate v-model="gradeValue" text-color="#ff9900" score-template="{value}" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              :disabled="iscomment" @change="rate(gradeValue)">
            </el-rate>
          </div>
          <!--如果用原生js实现此功能比较麻烦-->
          <div class="pinglun">
            <span style="width:100px">用户评论:</span>
            <input type="text" v-model='chatContent' style="border: transparent;
            width: 100%;">
          </div>
          <a class="send" @click.stop='sendComment()'>
            提 交
          </a>
        </div>
      </div>
      <div class="mc2" v-show='isShowMc2' @click.stop='isShowMc2=false'>
        <div @click.stop='isShowMc2=true'>
          <a class="buyBtn" @click="">购买课程</a>
          <a class="cancel" @click.stop='isShowMc2=false'>取消</a>
        </div>
      </div>
      <!-- <div class='btnBox' v-show='isShowBtnBox'> -->
      <!-- <div class='btnBox'>
                <router-link :to='{name: "setInfo",query:{id: cid}}'>编辑课程</router-link>
                <router-link to='/beginLive'>开始直播</router-link>
            </div> -->
    </div>
  </div>
</template>
<script>
  import {
    Loadmore
  } from 'mint-ui';
  import {
    formatDate
  } from '../../common/date.js'
  import courseIntroduction from '../../components/homeDetail/courseIntroduction.vue'
  import videoPlayback from '../../components/homeDetail/videoPlayback.vue'
  import liveClass from '../../components/homeDetail/liveClass.vue'
  export default {
    data() {
      return {
        username: '',
        img: '', //视频显示的图片
        score: 'undefined', //用户打过分
        isUpload: true,
        iscomment: false, //是否评价过 默认否

        gender: '',
        show: {
          tab0: true,
          tab1: false,
          tab2: false,
        },
        currentVideo: {
          vid: '', //当前播放视频的id
          vname: '',
          vdoUrl: '',
        },
        showEdit: false, //是否可以编辑课程信息
        playImg: require("../../image/play.png"),
        vdotime: {
          currentTime: '',
          allTime: '',
        },
        isShowMc: false,
        isShowMc2: false,
        isShowBtnBox: false, //单节课编辑课程 开始直播
        isShowCreateSingle: false, //系列课
        infoObj: {}, //获取详情的接口对象
        cid: '', //课程id
        timeDrage: false, //拖拽状态
        rangeVal: 0, //input进度条初始值
        maxVal: '', //input进度条最大
        isShow: false, //点击的是否是自定义控件 防止冒泡
        // 评论
        isShowComment: false, //是否显示评论框
        gradeScore: 5, //综合评分
        chatContent: '非常满意，无可挑剔,内容满意,讲师满意,画面满意', //我发表的评论
        gradeValue: 5, //星级打分
        showStar: true, //是否显示用户星级评价 第一次显示
        gradeStatus: true, //用户是否打过分 默认没打过
        addlist: [{
            content: '非常不满意,内容不好,讲师不好,画面不好',
            show: false
          },
          {
            content: '不满意,内容不好,讲师不好,画面不好',
            show: false
          },
          {
            content: '一般，有待提升, 内容一般,讲师一般, 画面一般',

            show: false
          },
          {
            content: '满意,内容满意,讲师满意,画面满意',
            show: false
          },
          {
            content: '非常满意，无可挑剔,内容满意,讲师满意,画面满意',
            show: true
          }
        ], //添加评论
        //评论列表
        list: [], //评论列表
        sentPage: {
          page: 1, //分页累加
        }, //接口入参
        totalNum: 0, //总数据条数
        allLoaded: false,
        // value5: 3,  //评论列表用户的星级评分
        userid: '',

      }
    },
    components: {
      'course-introduction': courseIntroduction,
      'video-playback': videoPlayback,
      'live-class': liveClass,
      Loadmore,
    },
    methods: {
      test() {

      },
      // 显示评价框
      showComment() {
        if (this.isLogin()) {
          this.isShowComment = true;

        }
      },
      //评分
      rate(e) {
        this.addlist.forEach((element, i) => {
          element.show = false
          if ((e - 1) == i) {
            element.show = true
            this.chatContent = element.content
          }
        });
      },
      //发送评价
      sendComment() {
        this.cid = this.$route.query.id;
        this.getGradeStatus();
      },
      //获取用户打分状态
      getGradeStatus() {
        this.cid = this.$route.query.id;
        //用户打分
        const score = {
          cid: this.cid, //评价课程Id
          userid: localStorage.getItem("loginMobile"),
        }
        //获取打分状态 即用户是否打过分
        this.$api.post(this.$api.baseURLSchool, "course_data", score, r => {
          this.score = r.data.ret;
          console.log(this.score)
          if (this.score != 0) {
            this.isShowComment = false;
            this.$utils._toast('每个用户只能评论一次哦')
            return;
          }
          // 用户打分
          const score = {
            cid: this.cid, //评价课程Id
            userid: localStorage.getItem("loginMobile"),
            mark: this.gradeValue, //打分
          }
          // 如果没打分，就打分
          if (this.gradeStatus) {
            this.$api.post(this.$api.baseURLSchool, "play_times", score, r => {
              // console.log(r);
            }, err => {
              console.log(err);
            })
          }
          //发表评价
          const params = {
            cid: this.cid, //评价课程Id
            userid: localStorage.getItem("loginMobile"),
            content: this.chatContent, //评价内容
            mark: this.gradeValue, //打分
          }
          if (this.chatContent) {
            this.$api.post(this.$api.baseURLSchool, "play_comment", params, r => {
              // console.log(r);
              //更新评价列表
              this.sentPage.page = 1;
              this.getCommentList(this.sentPage);
              // this.chatContent = "";
            }, err => {
              console.log(err);
              this.$utils._toast("评价失败");
            })
            this.isShowComment = false;
          } else {
            this.$utils._toast("评价不可为空~");
          }
        }, err => {
          console.log(err);
        })
      },




      tabToggle(index) {
        // $(this).addClass('active').siblings().removeClass();
        if (index == 0) {
          this.show.tab0 = true;
          this.show.tab1 = false;
          this.show.tab2 = false;
        } else if (index == 1) {
          this.show.tab0 = false;
          this.show.tab1 = true;
          this.show.tab2 = false;
        } else if (index == 2) {
          this.show.tab0 = false;
          this.show.tab1 = false;
          this.show.tab2 = true;
        }
      },
      isLogin() {
        if (!this.userid) {
          console.log(this.userid)
          this.$utils._toast('请先登录!');
          return false;
        } else {
          return true;
        }
      },

      //play
      play(item) {
        const vdoDom = document.getElementById('vdo');
        console.log('***/', vdoDom)
        if (vdoDom.paused) {
          this.playImg = require("../../image/pause.png");
          vdoDom.play();
        } else {
          this.playImg = require("../../image/play.png");
          vdoDom.pause();
        }
      },

      //获取当前课程的评价
      getCommentList(params) {
        this.sentPage.cid = this.$route.query.id;
        this.$api.post(this.$api.baseURLSchool, "collage_page/comment_user", params, r => {
          // console.log(r);
          if (r.data.ret == -3) {
              localStorage.clear();
              this.isLogin()
            }
          if (this.sentPage.page == 1) {
            this.list = r.data.rows;
          } else {
            this.list = this.list.concat(r.data.rows);
          }
          if (r.data.rows.length == 0 && this.sentPage.page > 1) {
            this.$utils._toast("暂无评价");
          }

          //获取每个用户的评价星级
          this.list.forEach((val, index) => {
            //用户打分
            const score = {
              cid: val.cid, //评价课程Id
              userid: val.id,
            }
            //获取打分状态 即用户是否打过分
            this.$api.post(this.$api.baseURLSchool, "course_data", score, r => {
              // console.log(r);
              if (r.data.ret == 1) {
                this.$set(this.list[index], 'value5', parseInt(r.data.info.mark));
              }
            }, err => {
              console.log(err);
            })

          });
        }, err => {
          console.log(err);
        })

      },
      //评价上拉加载
      loadBottom() {
        (this.sentPage.page) ++;
        setTimeout(() => {
          this.getCommentList(this.sentPage);
        }, 20);
        if (this.totalNum == this.list.length) {
          this.allLoaded = true;
        }
        this.$refs.loadmore.onBottomLoaded();
      },
      //控制视频控件显示隐藏
      controlShow() {
        this.isShow = false;
        $('.controls').slideToggle();
      },
      stopControl() {
        this.isShow = true;
      },
      //gofullScreen
      gofullScreen() {
        const vdoDom = document.getElementById('vdo');
        const params = {
          url: vdoDom.currentSrc,
          currentTime: vdoDom.currentTime,
          ispaused: vdoDom.paused
        };
        this.$router.push({
          name: 'fullScreen',
          query: params
        });
      },
      goBack() {


        if (this.$route.query.type == 'collect') {
          this.$router.push({
            path: '/myCollect'
          })
        } else if (this.$route.query.type == 'liveZone') {
          this.$router.push({
            path: '/liveZone'
          })
        } else if (this.$route.query.type == 'myCourse') {
          this.$router.push({
            path: '/myCourse'
          })
        } else if (this.$route.query.type == 'columndetail') {
          this.$router.push({
            path: '/columndetail',
            query: {
              id: this.$route.query.typeId
            }
          })
        } else {
          this.$router.push({
            path: '/home'
          })

        }
        // this.$router.back();
        // window.history.back();
      },
      //获取子组件传来的url
      getVdoByChild(url, id, vname) {
        //获取当前播放视频的id
        this.currentVideo.vid = id;
        this.currentVideo.vname = vname;
        this.currentVideo.vdoUrl = url;
        const vdoDom = document.getElementById('vdo');
        vdoDom.pause();
        this.playImg = require("../../image/play.png");
      },
      showMc2(isShowMc2) {
        this.isShowMc2 = isShowMc2;
      },
      //监测视频播放进度
      playTime() {
        const vdoDom = document.getElementById('vdo');
        this.vdotime.currentTime = this.$utils.vdoTime(vdoDom.currentTime);
        var currentPos = vdoDom.currentTime; //Get currenttime
        var maxduration = vdoDom.duration; //Get video duration
        var percentage = 100 * currentPos / maxduration; //in %
        $('.range').css('width', percentage + '%');
        this.rangeVal = currentPos;
      },
      //拖拽进度条
      playRange(e) {
        this.timeDrage = true;
        const vdoDom = document.getElementById('vdo');
        var that = this;
        $(e.target).on('touchend', function () {
          vdoDom.currentTime = $(e.target).val();
          that.vdotime.currentTime = that.$utils.vdoTime(vdoDom.currentTime);
          that.timeDrage = false;
        });

      },
      //获取视频播放总时长
      getallTime() {
        const fullScreen = JSON.parse(localStorage.getItem("fullScreen"));
        const vdoDom = document.getElementById('vdo');
        if (fullScreen) {
          vdoDom.currentTime = fullScreen.currentTime;
          this.currentVideo.vdoUrl = fullScreen.url;
          if (!fullScreen.ispaused) {
            vdoDom.play();
            this.playImg = require("../../image/pause.png");
          } else {
            vdoDom.pause();
            this.playImg = require("../../image/play.png");
          }
          setTimeout(function () {
            localStorage.setItem("fullScreen", 0);
          }, 2000);
        }

        this.vdotime.currentTime = this.$utils.vdoTime(vdoDom.currentTime);
        this.vdotime.allTime = this.$utils.vdoTime(vdoDom.duration);
        this.maxVal = vdoDom.duration;
      },
      init() {
        this.username = localStorage.getItem('doctorName')
        if (JSON.parse(localStorage.getItem('type')) == 'doctor' || JSON.parse(localStorage.getItem('type')) ==
          'clinic') {
          this.isUpload = true

        } else {
          this.isUpload = false
        }
        if (this.$route.query.name == 'createSingle') {
          this.isShowBtnBox = true;
        } else if (this.$route.query.name == 'createSeries') {
          this.isShowCreateSingle = true;
        }
        if (this.$route.query.user == 'self') { //从我的主页进来 可编辑课程信息
          this.showEdit = true;
        }
      },
      //根据课程id查video表 默认显示第一节
      getVideoByCid() {
        this.cid = this.$route.query.id;
        if (this.$route.query.vdoProgress) {
          const vdoProgress = JSON.parse(this.$route.query.vdoProgress);
          if (vdoProgress.vid) {
            this.currentVideo.vid = vdoProgress.vid;
            this.$api.get(this.$api.baseURLSchool, "select_cid/video/" + this.currentVideo.vid, {}, r => {
              if (r.data.ret == 1) {
                const vdoDom = document.getElementById('vdo');
                this.currentVideo.vname = r.data.info.v_name;
                this.currentVideo.vdoUrl = r.data.info.url;
                vdoDom.currentTime = vdoProgress.progress;
              }
              // this.infoObj = r.data.info;
            }, err => {
              console.log(err);
            })
          }
        } else {
          this.$api.get(this.$api.baseURLSchool, "selectdata2/video?cid=" + this.cid, {}, r => {
            // console.log(r);
            if (r.data.ret == 1) {
              if (r.data.info.length > 0) {
                const index = r.data.info.length - 1;
                //获取当前播放视频的id
                this.currentVideo.vid = r.data.info[index].id;
                this.currentVideo.vname = r.data.info[index].v_name;
                this.currentVideo.vdoUrl = r.data.info[index].url;
                // console.log(this.currentVideo);
                this.getallTime();
              } else {
                this.$utils._toast("课程中暂时没有视频哦");
              }
            }
          }, err => {
            console.log(err);
          })
        }

      },
      //获取课程详情
      getDetailsData() {
        this.cid = this.$route.query.id;
        this.$api.get(this.$api.baseURLSchool, "select_cid/view_course_user/" + this.cid, {}, r => {
          this.infoObj = r.data.info;
          if (this.infoObj.charge == null) {
            this.infoObj.charge = 0
          }
        }, err => {
          console.log(err);
        })
      },

    },
    computed: {

    },
    filters: {
      formatDate(time) {
        var now = formatDate(new Date(), 'yyyy-MM-dd hh:mm');
        var nowHeader = now.substring(0, 10);
        var commentHeader = time.substring(0, 10);
        // 如果是当天 就不显示评论的年月日
        if (nowHeader == commentHeader) {
          return time.substring(10);
        } else {
          return time;
        }
      },
    },
    created() {
      this.img = this.$route.query.poster;
      this.init();
      this.getDetailsData();
      this.getVideoByCid();
      this.getCommentList(this.sentPage);

    },
    mounted() {
      this.userid = localStorage.getItem("loginMobile");

    },
    //离开路由触发
    beforeRouteLeave(to, from, next) { //记录离开时的位置
      const vdoDom = document.getElementById('vdo');
      const play_progress = vdoDom.currentTime.toFixed(1);
      //视频播放 存入我的课程, //获取播放进度
      const content = {
        vid: this.currentVideo.vid,
        progress: play_progress
      };
      // console.log(content);
      this.$api.post(this.$api.baseURLSchool, "watch/user_relative?user_id=" + localStorage.getItem("loginMobile") +
        "&type_name=app8&type=app8&name=person21&rel_id=" + this.cid, content, r => {
          // console.log(r);
        }, err => {
          console.log(err);
        });
      next();
    },
  }

</script>
<style lang="scss" scoped>
  .pinglun {
    padding: 0px 10px 0px 15px;
    font-size: 14px;
    display: flex;

    li {
      height: 50px;
      line-height: 25px;
      display: flex;
      align-items: center;
    }

    label {
      margin-left: 10px;
      font-size: 14px;
    }
  }

  .remind {
    display: flex;
    justify-content: center;
    border-bottom: 1px dotted #e5e5e5;
    margin: 0rem 0.15rem;
    padding-bottom: 0.13rem;

    img {
      width: 1.44rem;
      height: 0.72rem;
    }
  }

  .vjs-custom-skin>.video-js .vjs-control {
    flex: 1
  }

  .mcCommentList {
    padding: 40px 0;

    img {
      display: block;
      width: 110px !important;
      height: 143px;
      margin: 0 auto;
    }

    p {
      padding-top: 10px;
      text-align: center;
    }
  }

</style>
